import { useJwt } from "@vueuse/integrations/useJwt";
// 缓存版本
export default defineCachedEventHandler(async (event) => {
  const token = getCookie(event, "Authorization");
  // 无token
  if (!token) {
    throw createError({
      status: 401,
      message: "Unauthorized",
    });
  }
  // 坏token
  const { payload } = useJwt<JwtPayLoad & JwtWithTimeOut>(token, {
    onError() {
      throw createError({
        status: 401,
        message: "Unauthorized",
      });
    },
  });
  // jwt 解码错误 或 jwt 过期
  if (!payload.value || payload.value.exp < Date.now() / 1000) {
    setCookie(event, "Authorization", "", { maxAge: 0 });
    return;
  }
  // query db
  const email = payload.value.email;
  // const user = await db<UserType>("users").where({ email }).first();
  // jwt 解码错误 或 jwt 过期
  const storage = useStorage("data");
  try {
    // const user = await storage.getItem<>("user");
    const user = await storage.getItem<JSONed<ReqPayLoad<UserType>>>("user");
    if (user) {
      return user.json;
    }
    else {
      throw createError({
        status: 401,
        message: "Unauthorized",
      });
    }
  }
  catch (e: any) {
    throw createError({
      status: 401,
      message: "Unauthorized",
    });
  }
});
